package net.sourceforge.cath.aspects.alsb;



import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.CodeSignature;

import net.sourceforge.cath.context.Context;
import net.sourceforge.cath.context.LoggingUnit;
import net.sourceforge.cath.logging.Logger;


public abstract aspect AlsbTracerAspect {
	pointcut scope();
	
	ThreadMXBean threadMxBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
	Logger logger = Logger.getInstance();
	
	Object around(): scope(){
		LoggingUnit unit = new LoggingUnit();
		String transactionId="empty";
		String localTransactionId = "L"+String.valueOf(System.currentTimeMillis());
		transactionId=Context.getGlobalTransactionId();
		unit.setTransactionId(transactionId);
		unit.setLocalTransactionId(localTransactionId);
		unit.setStartTime(System.currentTimeMillis());
		unit.setStartCpuTime(threadMxBean.getCurrentThreadCpuTime());
		unit.setSignature(thisJoinPoint.getSignature());
		
		Context.push(unit);
		logger.startLocalTransaction(unit);
		
		try{
			return proceed();
		}finally{
			unit.setEndTime(System.currentTimeMillis());
			unit.setEndCpuTime(threadMxBean.getCurrentThreadCpuTime());
	
			String pipelineContext = getPipelineContext(thisJoinPoint);
			unit.setNote(pipelineContext);
			logger.endLocalTransaction(unit);
			//logger.flush();
			Context.pop();

		}// try
	}
	
	public  String getPipelineContext(JoinPoint point){
		String pipelineContext=null;
		Object[] args = point.getArgs();
		Class[] types = ( (CodeSignature)point.getSignature()).getParameterTypes();
		
		for(int i=0;i<args.length;i++){
			if(args[i] == null ) continue;
			if(types[i].getName().equals("com.bea.wli.sb.pipeline.PipelineContext")){
				return types[i].getName()+":"+args[i];
			}
		}// fo
		
		return pipelineContext;
	}
}


